<template>
  <div class="role-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="角色名称">
              <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
            </el-form-item>
            <el-form-item label="权限字符">
              <el-input v-model="searchForm.roleKey" placeholder="请输入权限字符" clearable />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleKey" label="权限字符" />
        <el-table-column prop="sortOrder" label="显示顺序" width="90" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handlePermission(scope.row)">分配权限</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="sortOrder">
          <el-input-number v-model="roleForm.sortOrder" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScope">
          <el-select v-model="roleForm.dataScope" placeholder="请选择数据范围">
            <el-option :value="1" label="全部数据权限" />
            <el-option :value="2" label="自定义数据权限" />
            <el-option :value="3" label="本部门数据权限" />
            <el-option :value="4" label="本部门及以下数据权限" />
            <el-option :value="5" label="仅本人数据权限" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :props="{ label: 'title' }"
        :default-checked-keys="checkedPermissions"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleApi, menuApi } from '@/api/system'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleKey: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 角色表单对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)
const roleForm = reactive({
  roleId: null,
  roleName: '',
  roleKey: '',
  sortOrder: 0,
  dataScope: 1,
  status: 1,
  remark: '',
  menuIds: []
})

// 表单校验规则
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入权限字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入显示顺序', trigger: 'blur' }
  ]
}

// 权限设置对话框
const permissionDialogVisible = ref(false)
const permissionTreeRef = ref(null)
const currentRole = ref(null)
const permissionTree = ref([])
const checkedPermissions = ref([])

// 初始化
onMounted(() => {
  handleSearch()
  fetchMenuTree()
})

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    // 获取所有可用菜单树，使用一个默认角色ID（如1，表示管理员角色）
    const res = await roleApi.getRoleMenuTree(1)
    if (res.data) {
      // 将新的数据格式转换为树形结构
      permissionTree.value = transformMenuData(res.data)
    }
  } catch (error) {
    console.error('获取菜单树失败', error)
    ElMessage.error('获取菜单树失败')
  }
}

// 转换菜单数据为树形结构
const transformMenuData = (menuData) => {
  if (!menuData || menuData.length === 0) return []
  
  // 创建一个映射，用于快速查找父节点
  const menuMap = {}
  const rootMenus = []
  
  // 第一步：将所有菜单放入映射
  menuData.forEach(item => {
    const menuItem = {
      id: item.menuId,
      title: item.menuName,
      path: item.path,
      component: item.component,
      permission: item.permission,
      icon: item.icon,
      parentId: item.parentId,
      menuType: item.menuType,
      sortOrder: item.sortOrder,
      status: item.status,
      children: []
    }
    
    menuMap[item.menuId] = menuItem
  })
  
  // 第二步：构建树形结构
  menuData.forEach(item => {
    const menuItem = menuMap[item.menuId]
    
    if (item.parentId === 0) {
      // 这是一个根菜单
      rootMenus.push(menuItem)
    } else {
      // 这是一个子菜单，将其添加到父菜单的children中
      const parentMenu = menuMap[item.parentId]
      if (parentMenu) {
        parentMenu.children.push(menuItem)
      }
    }
  })
  
  // 根据sortOrder排序
  const sortMenus = (menus) => {
    menus.sort((a, b) => a.sortOrder - b.sortOrder)
    menus.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        sortMenus(menu.children)
      }
    })
    return menus
  }
  
  return sortMenus(rootMenus)
}

// 搜索方法
const handleSearch = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await roleApi.getList(params)
    if (res.data) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  handleSearch()
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  roleForm.roleId = null
  roleForm.roleName = ''
  roleForm.roleKey = ''
  roleForm.sortOrder = 0
  roleForm.dataScope = 1
  roleForm.status = 1
  roleForm.remark = ''
  roleForm.menuIds = []
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  try {
    const res = await roleApi.getDetail(row.roleId)
    if (res.data) {
      const roleDetail = res.data
      dialogType.value = 'edit'
      roleForm.roleId = roleDetail.roleId
      roleForm.roleName = roleDetail.roleName
      roleForm.roleKey = roleDetail.roleKey
      roleForm.sortOrder = roleDetail.sortOrder
      roleForm.dataScope = roleDetail.dataScope
      roleForm.status = roleDetail.status
      roleForm.remark = roleDetail.remark
      roleForm.menuIds = roleDetail.menuIds || []
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取角色详情失败', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该角色吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await roleApi.delete(row.roleId)
      ElMessage.success('删除成功')
      handleSearch()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await roleApi.add(roleForm)
          ElMessage.success('添加成功')
        } else {
          await roleApi.update(roleForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        handleSearch()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败' : '修改失败', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
      }
    }
  })
}

// 打开权限设置对话框
const handlePermission = async (row) => {
  currentRole.value = row
  try {
    // 获取角色已有的菜单权限
    const res = await roleApi.getRoleMenuList(row.roleId)
    checkedPermissions.value = res.data || []
    
    // 获取该角色可分配的菜单树
    const menuRes = await roleApi.getRoleMenuTree(0)
    if (menuRes.data) {
      // 将新的数据格式转换为树形结构
      permissionTree.value = transformMenuData(menuRes.data)
    }
    permissionDialogVisible.value = true
    console.log('角色id', row.roleId)
    console.log('获取菜单配置', permissionTree.value.filter(m => res.data.includes(m.id)))

    console.log('获取角色菜单权限', res.data)
  } catch (error) {
    console.error('获取角色菜单权限失败', error)
    ElMessage.error('获取角色菜单权限失败')
  }
}

// 提交权限设置
const handlePermissionSubmit = async () => {
  if (!permissionTreeRef.value || !currentRole.value) return
  
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
  
  try {
    await roleApi.updateRoleMenu({
      roleId: currentRole.value.roleId,
      menuIds: allCheckedKeys
    })
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('权限设置失败', error)
    ElMessage.error('权限设置失败')
  }
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.search-form {
  margin-right: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 